package com.epfresh.supplier.delegate;

import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.epfresh.api.entity.FileUploadResponse;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.ucrop.PhotoCore;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.L;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.supplier.R;
import com.epfresh.supplier.adapter.GridViewAdapter;
import com.epfresh.supplier.entity.Images;
import com.google.gson.Gson;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wzh on 2016/5/6.
 */
public class UploadProductDelegate implements PhotoCore.PhotoResult {


    private boolean isSelect;
    private BaseActivity context;

    private GridView dgv;
    private GridViewAdapter adapter;


    private List<Images> imgList = new ArrayList<>();

    private int currentIndex = -1;
    private PhotoCore photoCore;


    private String filePath = FileUtil.getImgCacheDir() + "/" + "product_detail";

    private boolean isFirst;

    private String description = "";
    private String images = "";

    private String productId = "";

    public UploadProductDelegate(BaseActivity context) {
        this.context = context;

        filePath += "_" + ApplicationHelper.getInstance().getUser().getAccountId();
        initView();
        initPhotoCore();
    }

    public void setMaxLimit(int num) {
        if (adapter != null) {
            adapter.setImgMaxSize(num);
        }
    }
    public PhotoCore getPhotoCore() {
        return photoCore;
    }

    private void initPhotoCore() {
        photoCore = new PhotoCore(this, context);
        photoCore.setRatio(4, 3);
        photoCore.setResultHeight(500);
        photoCore.setResultWidth(500);
    }

    public List<Images> getImages(){
        if (adapter != null){
            return adapter.getImages();
        }
        return null;
    }
    public boolean isUploadNotSuccess() {
        if (adapter != null){
            return adapter.isUploadNotSuccess();
        }
        return false;
    }

    public String getImagesStr() {
        if (adapter != null) {
            List<Images> images = adapter.getImages();
            if (images != null) {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < images.size(); i++) {
                    if (i != 0){
                        sb.append(",");
                    }
                    sb.append(images.get(i).getId());
                }

                if (sb.length() > 0){
                    return sb.toString();
                }
            }
        }
        return null;
    }
    public List<String> getImagesStrList() {
        if (adapter != null) {
            List<Images> images = adapter.getImages();
            if (images != null) {
                ArrayList<String> list = new ArrayList<>();

                for (int i = 0; i < images.size(); i++) {
                    list.add(String.valueOf(images.get(i).getId()));
                }

                return list;
            }
        }
        return null;
    }


    public List<String> getImagesPngList() {
        if (adapter != null) {
            List<Images> images = adapter.getImages();
            if (images != null) {
                ArrayList<String> list = new ArrayList<>();

                for (int i = 0; i < images.size(); i++) {
                    list.add(images.get(i).getFilePath());
                    Log.e("image"+i,images.get(i).toString());
                }

                return list;
            }
        }
        return null;
    }


    public boolean isSelect() {
        return isSelect;
    }

    public void setSelect(boolean select) {
        isSelect = select;
    }

    public void setImgList(List<Images> imgList){
        this.imgList.clear();
        if (imgList != null &&imgList.size() > 0 ){
            this.imgList.clear();
            this.imgList.addAll(imgList);

            adapter.clearAllStatus();
        }
        adapter.addedView();
        reSize(this.imgList.size());
    }

    private void initView() {

        dgv = (GridView) context.findViewById(R.id.dgv);
//        ViewGroup.LayoutParams layoutParams = dgv.getLayoutParams();
//        layoutParams.height = LocalDisplay.SCREEN_WIDTH_PIXELS / 3 * 2;
        adapter = new GridViewAdapter(context, imgList);
        dgv.setAdapter(adapter);

        adapter.setOnDeleteListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reSize(imgList.size());
            }
        });

        dgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                isSelect = true;
//                currentPhotoUpload = (PhotoUploadView) view;
                Images images = imgList.get(position);

                //添加图片或者上传图片失败
                if (images.isAdd()) {
                    currentIndex = position;
                    String fp = images.getFilePath();
                    if (fp == null || "".equals(fp)) {
                        images.setFilePath(new File(filePath + "_" + System.currentTimeMillis()).getPath());
                    }

                    photoCore.showPhotoDialog(Uri.fromFile(new File(images.getFilePath())), images.getFilePath(),images.isUploadFail());
                } else if (images.isUploadFail()) {
                    images.setType(Images.LOADING);
                    adapter.notifyDataSetChanged();
                    RequestTag tag = new RequestTag();
                    tag.action = currentIndex;
                    tag.tag = "upload";
                    tag.arg1 = images.getUuid();
                    photoCore.uploadImage(context, images.getFilePath(), tag, uploadListener);
                }


            }
        });


        displayData();
    }


    //加载数据
    private void displayData() {
//        Intent data = getIntent();
//        images = data.getStringExtra("product_images");
//        description = data.getStringExtra("product_description");
//
//
//        L.e("images", "images:" + images);
//        if (!TextUtils.isEmpty(images)) {
//            List<Images> imagesList = new Gson().fromJson(images, new TypeToken<List<Images>>() {
//            }.getType());
//            imgList.clear();
//
//            int bannerCount = 0;
//            int detailCount = 0;
//            for (int i = 0; i < imagesList.size(); i++) {
//                Images images1 = imagesList.get(i);
//
//
//                boolean cover = images1.isCover();
//                boolean banner = images1.isBanner();
//
//                if (banner) {
//
//                } else if (detailCount < 6) {
//                    imgList.add(images1);
//
//                    detailCount++;
//                }
//
//
//            }
//
//
//            adapter.clearAllStatus();
//        }


        reSize(imgList.size());
        adapter.addedView();

    }


    OnRequestListener<FileUploadResponse> uploadListener = new OnRequestListener<FileUploadResponse>() {
        @Override
        public FileUploadResponse jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, FileUploadResponse.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            Log.e("upload", "upload_fail");
            if (tag instanceof RequestTag) {
                RequestTag rt = (RequestTag) tag;
                adapter.updateStatus(rt.arg1, null, Images.LOAD_FAIL);
            }

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (tag instanceof RequestTag) {
                RequestTag rt = (RequestTag) tag;
                adapter.updateStatus(rt.arg1, null, Images.LOAD_FAIL);
            }
            Log.e("upload", "upload_error");
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<FileUploadResponse> response, Object tag) {
            FileUploadResponse responseElement = response.getResponseElement();
            int id = responseElement.getId();
            Log.e("upload", "id=" + id);
            if (tag instanceof RequestTag) {
                RequestTag rt = (RequestTag) tag;

                adapter.updateStatus(rt.arg1, id + "", Images.SUCCESS);
            }


        }
    };

    @Override
    public void onSuccess(String path) {
        L.e("test", "path:" + path + "");
        isSelect = false;
        if (currentIndex > -1 && currentIndex < imgList.size()) {
            Images images = imgList.get(currentIndex);

//            images.setFilePath(path);
            images.setType(Images.LOADING);
            adapter.clearAllStatus();
            adapter.addedView();
            RequestTag tag = new RequestTag();
            tag.action = currentIndex;
//            currentIndex = -1;
            tag.tag = "upload";
            tag.arg1 = images.getUuid();
            photoCore.uploadImage(context, images.getFilePath(), tag, uploadListener);


            reSize(imgList.size());
        }
    }

    @Override
    public void onFail(String msg) {
        isSelect = false;
        T.toast("获取图片失败");
    }

    @Override
    public void onReupload() {
        isSelect = false;
        if (currentIndex > -1 && currentIndex < imgList.size()) {
            Images images = imgList.get(currentIndex);
            images.setType(Images.LOADING);
            adapter.notifyDataSetChanged();
            RequestTag tag = new RequestTag();
            tag.action = currentIndex;
            tag.tag = "upload";
            tag.arg1 = images.getUuid();
            photoCore.uploadImage(context, images.getFilePath(), tag, uploadListener);
        }
    }


    public void reSize(int size){
        if (size > 3) {
            ViewGroup.LayoutParams layoutParams = dgv.getLayoutParams();
            layoutParams.height = (LocalDisplay.SCREEN_WIDTH_PIXELS  - LocalDisplay.dp2px(40))/4 * 2 + LocalDisplay.dp2px(36);
        } else {
            ViewGroup.LayoutParams layoutParams = dgv.getLayoutParams();
            layoutParams.height = (LocalDisplay.SCREEN_WIDTH_PIXELS  - LocalDisplay.dp2px(40))/4 + LocalDisplay.dp2px(24);
        }
    }

}
